from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from django.conf import settings
from utils.exceptions import CustomError


class TenCenCos:
    def __init__(self):
        self.secret_id = settings.TENCENT_CLOUD['TENCENT_SECRETID']  # 替换为用户的secret_id
        self.secret_key = settings.TENCENT_CLOUD['TENCENT_SECRETKEY']  # 替换为用户的secret_key
        self.region = settings.TENCENT_CLOUD['REGION']  # 替换为用户的region
        self.config = CosConfig(Region=self.region, SecretId=self.secret_id, SecretKey=self.secret_key,
                                Token=None)  # 获取配置对象
        self.client = CosS3Client(self.config)
        self.bucket = settings.TENCENT_CLOUD['BUCKET']

    def upload(self, local_filepath, save_path):
        # 本地路径 简单上传
        try:
            response = self.client.upload_file(
                Bucket=self.bucket,
                LocalFilePath=local_filepath,
                Key=save_path,
                PartSize=10,
                MAXThread=10
            )
            return response
        except Exception as e:
            raise CustomError('文件上传失败')

    def deleteObject(self, save_path):
        # 删除object
        response = self.client.delete_object(
            Bucket=self.bucket,
            Key=save_path
        )
        print(response)
